package com.android.nodejs.livejs.activities;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.Toast;

import com.android.nodejs.livejs.R;
import com.android.nodejs.livejs.services.MessageService;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class MainActivity extends SlidingFragmentActivity {
    private ViewPager mViewPager;
    private TabHost mTabHost;
    TabWidget mTabWidget;
    public HashMap<String, TabInfo> mTabs = new HashMap<String, TabInfo>();

    //private MenuItem add;
    private Intent intent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setBehindContentView(R.layout.content_menu);
        setContentView(R.layout.content_application);
        SlidingMenu sm = getSlidingMenu();
        sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        sm.setShadowWidthRes(R.dimen.shadow_width);
        sm.setShadowDrawable(R.drawable.shadow);
        sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        sm.setFadeDegree(0.35f);
        // sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        initialiseTabHost(savedInstanceState);
        initComponents();
        addListenners();
        mTabHost.setCurrentTab(0);
    }

    private void initComponents() {
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        mViewPager.setAdapter(new ContentFragmentPagerAdapter(getSupportFragmentManager()));
        // start ChatMessageService
        intent = new Intent(this, MessageService.class);
        this.startService(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        //this.stopService(intent);
        Log.d("SERVICE", "onStop - stoped message service");
    }

    private void initialiseTabHost(Bundle args) {
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        mTabWidget = (TabWidget) findViewById(android.R.id.tabs);
        mTabHost.setup();

        TabInfo tabInfo = new TabInfo("Tab1", MessageFragment.class, args);
        tabInfo.fragment = new MessageFragment();
        addTab(tabInfo, R.drawable.tab_messages_selected, args);

        tabInfo = new TabInfo("Tab2", FriendFragment.class, args);
        tabInfo.fragment = new FriendFragment();
        addTab(tabInfo, R.drawable.tab_friends_selected, args);

        tabInfo = new TabInfo("Tab3", InvitationFragment.class, args);
        tabInfo.fragment = new InvitationFragment();
        addTab(tabInfo, R.drawable.tab_invitations_selected, args);

        tabInfo = new TabInfo("Tab4", ChatFragment.class, args);
        tabInfo.fragment = new ChatFragment();
        addTab(tabInfo, R.drawable.tab_chats_selected, args);
    }

    /**
     * Add Tab content to the Tabhost
     * 
     * @param activity
     * @param tabHost
     * @param tabSpec
     * @param clss
     * @param args
     */
    private void addTab(TabInfo tabInfo, int iconResId, Bundle bundle) {

        mTabs.put(tabInfo.tag, tabInfo);
        TabSpec tabSpec = mTabHost.newTabSpec(tabInfo.tag);
        View indicator = LayoutInflater.from(MainActivity.this).inflate(R.layout.tab_item, mTabWidget, false);
        ((ImageView) indicator.findViewById(R.id.tab_icon)).setImageResource(iconResId);
        tabSpec.setIndicator(indicator);
        tabSpec.setContent(new TabFactory(MainActivity.this));
        mTabHost.addTab(tabSpec);
    }

    /**
     * (non-Javadoc)
     * 
     * @see android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String)
     */
    public void onTabChanged(String tag) {
        // TabInfo newTab = this.mapTabInfo.get(tag);
        int pos = this.mTabHost.getCurrentTab();
        this.mViewPager.setCurrentItem(pos);
    }

    public void addListenners() {
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            public void onPageSelected(int position) {
                mTabHost.setCurrentTab(position);
            }

            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // nothing
            }

            public void onPageScrollStateChanged(int arg0) {
                // nothing
            }
        });
        mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {

            public void onTabChanged(String tabId) {
                mViewPager.setCurrentItem(mTabHost.getCurrentTab(), true);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.layout.content_menu, menu);
        showMenu();
        showContent();
        return true;
    }

    /*************************** Content Menu */
    public void onClickShowMenu(View v) {
        showMenu();
    }

    public void onClickProfile(View v) {
        Intent intent = new Intent();
        intent.setClass(this, ProfileActivity.class);
        startActivity(intent);
    }

    public void onClickChangePassword(View v) {
        Intent intentChangePassword = new Intent();
        intentChangePassword.setClass(getApplicationContext(), ChangePasswordActivity.class);
        startActivity(intentChangePassword);
    }

    public void onClickAbout(View v) {
        Intent intentAbout = new Intent();
        intentAbout.setClass(getApplicationContext(), AboutActivity.class);
        startActivity(intentAbout);
    }

    public void onClickSignOut(View v) {
        AlertDialog.Builder bui = new AlertDialog.Builder(MainActivity.this);
        bui.setMessage("Are you sure you want to logout?").setTitle("Sign Out confirm").setCancelable(false)
                .setNegativeButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Toast.makeText(getApplicationContext(), "Signed out", Toast.LENGTH_LONG).show();
                        // process sign out
                    }
                }).setPositiveButton("No", null);
        bui.create();
        bui.show();
    }

    public void onClickFeedback(View v) {
        try {
            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            String[] recipients = new String[] { "thaivu101@gmail.com" };
            String[] ccList = { "visaochotloe@gmail.com" };// email dang ky..
            emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients);
            emailIntent.putExtra(android.content.Intent.EXTRA_BCC, ccList);
            emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Feedback for LiveJS v1.0!");
            emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");
            emailIntent.setType("text/plain");
            startActivity(Intent.createChooser(emailIntent, "Send mail"));
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage().toString(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    public void onClickHelp(View v) {
        Intent intentHelp = new Intent();
        intentHelp.setClass(getApplicationContext(), HelpActivity.class);
        startActivity(intentHelp);
    }

    private class TabInfo {
        private String tag;
        // private Class<?> clss;
        // private Bundle args;
        private Fragment fragment;

        TabInfo(String tag, Class<?> clazz, Bundle args) {
            this.tag = tag;
            // this.clss = clazz;
            // this.args = args;
        }
    }

    class TabFactory implements TabContentFactory {

        private final Context mContext;

        /**
         * @param context
         */
        public TabFactory(Context context) {
            mContext = context;
        }

        public View createTabContent(String tag) {
            View v = new View(mContext);
            v.setMinimumWidth(0);
            v.setMinimumHeight(0);
            return v;
        }

    }

    protected void onSaveInstanceState(Bundle outState) {
        // save the tab selected
        outState.putString("tab", mTabHost.getCurrentTabTag());
        super.onSaveInstanceState(outState);
    }

    private class ContentFragmentPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<String> tags = new ArrayList<String>();

        public ContentFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
            tags.addAll(mTabs.keySet());
        }

        @Override
        public int getCount() {
            return tags.size();
        }

        @Override
        public Fragment getItem(int position) {
            return mTabs.get(tags.get(position)).fragment;
        }

    }

}
